<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ncduc
 * Date: 7/6/13
 * Time: 9:51 AM
 * To change this template use File | Settings | File Templates.
 */
include_once("../libs/setup.php");
include_once("../libs/helper.php");
session_start();

if (!check_user_session()) {
    header("Location: ../signin.php");
    return;
}
assign_home_header($smarty);
$smarty->assign('wwwUrl','../');
function is_valid_project($id, $cur_userId, mysqli $mysqli)
{
    $query = "SELECT * FROM de_tai_nghien_cuu WHERE Ma=$id";
    $result = $mysqli->query($query);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $id = $row['Ma'];
            $userId = $row['MaUser'];
            if ($userId == $cur_userId) {
                return true;
            }
        }

    }
    return false;

}

function load_research_projects(mysqli $mysqli, $userId, Smarty $smarty)
{
    $query = "SELECT * FROM de_tai_nghien_cuu WHERE MaUser=$userId";
    $result = $mysqli->query($query);
    $arr_research_projects = array();
    if ($result) {

        while ($row = $result->fetch_assoc()) {
            $arr_research_projects[] = array("Ma" => $row["Ma"],
                "TenDeTai_vi" => $row["TenDeTai_vi"],
                "TenDeTai_en" => $row["TenDeTai_en"],
                "TenToChucTaiTro_vi" => $row["TenToChucTaiTro_vi"],
                "TenToChucTaiTro_en" => $row["TenToChucTaiTro_en"],
                "DiaChi" => $row["DiaChi"],
                "DiaChiWebsite" => $row["DiaChiWebsite"],
                "VaiTro_vi" => $row["VaiTro_vi"],
                "VaiTro_en" => $row["VaiTro_en"],
                "ThoiGianBatDau" => $row["ThoiGianBatDau"],
                "ThoiGianKetThuc" => $row["ThoiGianKetThuc"],
                "TongKinhPhi" => $row["TongKinhPhi"],
                "DonViTienTe" => $row["DonViTienTe"],
                "ThongTinThem" => $row["ThongTinThem"]);
        }
    }
    if ($mysqli->error) {
        system_failed($mysqli->error, $smarty);
        $mysqli->close();
        return false;
    }
    $smarty->assign('projects', $arr_research_projects);
    return true;
}

function load_research_project(mysqli $mysqli, $projectId, Smarty $smarty)
{
    $query = "SELECT * FROM de_tai_nghien_cuu WHERE Ma=$projectId";
    $result = $mysqli->query($query);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $id = $row['Ma'];
            $project_name_vi = $row['TenDeTai_vi'];
            $project_name_en = $row['TenDeTai_en'];
            $main_org_vi = $row['TenToChucTaiTro_vi'];
            $main_org_en = $row['TenToChucTaiTro_en'];
            $address = $row['DiaChi'];
            $website = $row['DiaChiWebsite'];
            $role_vi = $row['VaiTro_vi'];
            $role_en = $row['VaiTro_en'];
            $fromDate = $row['ThoiGianBatDau'];
            $toDate = $row['ThoiGianKetThuc'];
            $currency = $row['DonViTienTe'];
            $fund = $row['TongKinhPhi'];
            $more_info = $row['ThongTinThem'];
            $smarty->assign('id', $id);
            $smarty->assign('project_name_vi', $project_name_vi);
            $smarty->assign('project_name_en', $project_name_en);
            $smarty->assign('main_org_vi', $main_org_vi);
            $smarty->assign('main_org_en', $main_org_en);
            $smarty->assign('address', $address);
            $smarty->assign('website', $website);
            $smarty->assign('role_vi', $role_vi);
            $smarty->assign('role_en', $role_en);
            $smarty->assign('fromDate', $fromDate);
            $smarty->assign('toDate', $toDate);
            $smarty->assign('currency', $currency);
            $smarty->assign('fund', $fund);
            $smarty->assign('more_info', $more_info);
        }
    }
    if ($mysqli->error) {
        system_failed($mysqli->error, $smarty);
        $mysqli->close();
        return false;
    }

    return true;
}

function add_research_project(mysqli $mysqli, array $project_info, Smarty $smarty)
{
    $sql = "INSERT INTO de_tai_nghien_cuu(MaUser, TenDeTai_vi, TenDeTai_en, TenToChucTaiTro_en,TenToChucTaiTro_vi,DiaChi,DiaChiWebsite,VaiTro_vi, VaiTro_en, ThoiGianBatDau,ThoiGianKetThuc,TongKinhPhi,DonViTienTe,ThongTinThem)
    VALUES({$project_info['user_id']},'{$project_info['project_name_vi']}','{$project_info['project_name_en']}','{$project_info['main_org_vi']}','{$project_info['main_org_en']}','{$project_info['address']}','{$project_info['website']}','{$project_info['role_vi']}','{$project_info['role_en']}',STR_TO_DATE('{$project_info['fromDate']}','%m-%Y'),STR_TO_DATE('{$project_info['toDate']}','%m-%Y'),'{$project_info['currency']}',{$project_info['fund']},'{$project_info['more_info']}')";
    $result = $mysqli->query($sql);
    if ($mysqli->error) {
        system_failed($mysqli->error . "sql: " . $sql, $smarty);
        $mysqli->close();
        return false;
    }
    return true;
}

function save_research_project(mysqli $mysqli, array $project_info, Smarty $smarty)
{
    $sql = "UPDATE de_tai_nghien_cuu SET  TenDeTai_vi='{$project_info['project_name_vi']}', TenDeTai_en='{$project_info['project_name_en']}', TenToChucTaiTro_vi='{$project_info['main_org_vi']}',TenToChucTaiTro_en='{$project_info['main_org_en']}', DiaChi='{$project_info['address']}',DiaChiWebsite='{$project_info['website']}',VaiTro_en='{$project_info['role_en']}',VaiTro_vi='{$project_info['role_vi']}', ThoiGianBatDau=STR_TO_DATE('{$project_info['fromDate']}','%m-%Y'), ThoiGianKetThuc=STR_TO_DATE('{$project_info['toDate']}','%m-%Y'), TongKinhPhi={$project_info['fund']},DonViTienTe='{$project_info['currency']}',ThongTinThem='{$project_info['more_info']}' WHERE Ma={$project_info['id']}";
    $result = $mysqli->query($sql);
    if ($mysqli->error) {
        system_failed($mysqli->error . "sql: " . $sql, $smarty);
        $mysqli->close();
        return false;
    }
    return true;
}

function delete_research_project(mysqli $mysqli, $projectId, Smarty $smarty)
{
    $sql = "DELETE FROM de_tai_nghien_cuu WHERE Ma=$projectId";
    $result = $mysqli->query($sql);
    if ($mysqli->error) {
        system_failed($mysqli->error . "sql: " . $sql, $smarty);
        $mysqli->close();
        return false;
    }
    return true;
}

function get_research_project_from_page()
{
    $project_info = array(
        'id' => addslashes($_REQUEST['id']),
        'user_id' => $_SESSION['ma_user'],
        'project_name_vi' => addslashes($_REQUEST['project_name_vi']),
        'project_name_en' => addslashes($_REQUEST['project_name_en']),
        'main_org_vi' => addslashes($_REQUEST['main_org_vi']),
        'main_org_en' => addslashes($_REQUEST['main_org_en']),
        'address' => addslashes($_REQUEST['address']),
        'website' => addslashes($_REQUEST['website']),
        'role_vi' => addslashes($_REQUEST['role_vi']),
        'role_en' => addslashes($_REQUEST['role_en']),
        'fromDate' => addslashes($_REQUEST['fromDate']),
        'toDate' => addslashes($_REQUEST['toDate']),
        'fund' => addslashes($_REQUEST['fund']),
        'currency' => addslashes($_REQUEST['currency']),
        'more_info' => addslashes($_REQUEST['more_info'])
    );
    if (empty($project_info['fund'])) {
        $project_info['fund'] = 0;
    }
    return $project_info;
}

$mysqli = connect_database($smarty);
$cur_userId = $_SESSION['ma_user'];
if (empty($_REQUEST['save']) && empty($_REQUEST['next'])) {
    if (!empty($_REQUEST['id']) && !empty($_REQUEST['action'])) {
        if (!is_valid_project($_REQUEST['id'], $cur_userId, $mysqli)) {
            $message = "Không tìm thấy đề tài";
            $smarty->assign('is_display', "block");
            $smarty->assign('message', $message);
        } else {
            if ($_REQUEST['action'] == "edit") {
                if (!load_research_project($mysqli, $_REQUEST['id'], $smarty)) {
                    return;
                }

            }
            if ($_REQUEST['action'] == "delete") {
                if (!delete_research_project($mysqli, $_REQUEST['id'], $smarty)) {
                    return;
                }
                $message = "Đã xóa thành công đề tài ";
                $smarty->assign('is_display', "block");
                $smarty->assign('type_message','success');
                $smarty->assign('message', $message);
            }
        }
    } else {
        $smarty->assign('id',null);
    }


} else {
    if (!empty($_REQUEST['save'])) {
        $project_info = get_research_project_from_page();
        if(empty($project_info['id']))
        {
            if(!add_research_project($mysqli,$project_info,$smarty))
            {
                return;
            }
            $message = "Thêm thành công đề tài mới";
                $smarty->assign('is_display', "block");
                $smarty->assign('type_message','success');
                $smarty->assign('message', $message);
        }
        else
        {
            if(!save_research_project($mysqli,$project_info,$smarty))
            {
                return;
            }
            $message = "Đã sửa thành công đề tài";
            $smarty->assign('is_display', "block");
            $smarty->assign('type_message','success');
            $smarty->assign('message', $message);
        }
    } else {
        header("Location: 4.php");
        return;
    }
}
//load data table
if (!load_research_projects($mysqli, $cur_userId, $smarty)) {
    return;
}
$smarty->assign('currency_array',array('VND','USD','EUR'));

$smarty->display('profile/4_1.tpl');